﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;

namespace RESP_IIWaterAssessment
{
    public partial class SchoolLossFormReport : Form
    {
        int regID, avpID, fhID, pfshID = -1, lossID, year;

        public SchoolLossFormReport()
        {
            InitializeComponent();
        }

        private void SchoolLossFormReport_Load(object sender, EventArgs e)
        {

            cbRegion.SelectedIndexChanged -= cbRegion_SelectedIndexChanged;
            cbRegion.DataSource = UtilClass.FillCBRegions();
            cbRegion.DisplayMember = "Name";
            cbRegion.ValueMember = "ID";

            if (InformationClass.isAdmin)
            {
                cbRegion.SelectedIndex = -1;
                cbRegion.Text = string.Empty;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
            }
            else
            {
                cbRegion.Enabled = false;
                regID = InformationClass.regionID;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
                cbRegion.SelectedValue = regID;
                cbRegion_SelectedIndexChanged(cbRegion, null);
                cbAVP.Enabled = true;
                cbAVP.Text = string.Empty;
                //toolStrip1.Visible = false;
            }

            for (int i = 1991; i < 2100; i++)
            {
                cbYear.Items.Add(i);
            }
            cbYear.SelectedIndex = cbYear.FindStringExact(DateTime.Now.Year.ToString());

            cbLoss.SelectedIndexChanged -= cbLoss_SelectedIndexChanged;
            if (InformationClass.Lang)
                cbLoss.DataSource = DBClass.Losses
                    .Select(se => new
                    {
                        ID = se.ID,
                        Name = se.Name
                    })
                    .Distinct().ToArray();
            else
                cbLoss.DataSource = DBClass.Losses
                    .Select(se => new
                    {
                        ID = se.ID,
                        Name = se.NameUz
                    })
                    .Distinct().ToArray();

            cbLoss.DisplayMember = "Name";
            cbLoss.ValueMember = "ID";
            cbLoss.SelectedIndex = -1;
            cbLoss.Text = string.Empty;
            cbLoss.SelectedIndexChanged += new EventHandler(cbLoss_SelectedIndexChanged);


        }

        private void cbRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbRegion.SelectedIndex >= 0)
            {
                cbAVP.Enabled = true;
                regID = Convert.ToInt32(cbRegion.SelectedValue);
                cbAVP.SelectedIndexChanged -= cbAVP_SelectedIndexChanged;
                cbAVP.DataSource = UtilClass.FillAVP(regID);
                cbAVP.ValueMember = "ID";
                cbAVP.DisplayMember = "Name";
                cbAVP.SelectedIndex = -1;
                cbAVP.Text = string.Empty;
                cbFH.DataSource = null;
                cbPFSH.DataSource = null;
                cbAVP.SelectedIndexChanged += new EventHandler(cbAVP_SelectedIndexChanged);
                pfshID = 0;
            }
        }

        private void cbAVP_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbAVP.SelectedIndex >= 0)
            {
                avpID = Convert.ToInt32(cbAVP.SelectedValue);
                cbFH.SelectedIndexChanged -= cbFH_SelectedIndexChanged;
                cbFH.Enabled = true;
                cbFH.DataSource = DBClass.Farms
                    .Where(wh => wh.AVPID == avpID)
                    .Select(se => new { ID = se.ID, Name = se.Name })
                    .OrderBy(o => o.Name)
                    .ToArray();
                cbFH.DisplayMember = "Name";
                cbFH.ValueMember = "ID";
                cbFH.SelectedIndex = -1;
                cbFH.Text = string.Empty;
                cbPFSH.DataSource = null;
                cbFH.SelectedIndexChanged += new EventHandler(cbFH_SelectedIndexChanged);
                pfshID = 0;
            }
        }

        private void cbFH_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbFH.SelectedIndex >= 0)
            {
                fhID = Convert.ToInt32(cbFH.SelectedValue);
                cbPFSH.Enabled = true;
                cbPFSH.SelectedIndexChanged -= cbPFSH_SelectedIndexChanged;
                cbPFSH.DataSource = DBClass.Schools
                    .Where(wh => wh.FarmID == fhID)
                    .Select(se => new { ID = se.ID, Name = se.Name })
                    .OrderBy(o => o.Name)
                    .ToArray();
                cbPFSH.DisplayMember = "Name";
                cbPFSH.ValueMember = "ID";
                cbPFSH.SelectedIndex = -1;
                cbPFSH.Text = string.Empty;
                cbPFSH.SelectedIndexChanged += new EventHandler(cbPFSH_SelectedIndexChanged);
                pfshID = 0;
            }
        }

        private void cbPFSH_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbPFSH.SelectedIndex >= 0)
            {
                pfshID = Convert.ToInt32(cbPFSH.SelectedValue);
            }
            else
            {
                pfshID = 0;
            }
        }

        private void cbYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbYear.SelectedIndex >= 0)
            {
                year = Convert.ToInt32(cbYear.Items[cbYear.SelectedIndex].ToString());
            }
            else
                year = DateTime.Now.Year;
        }

        private void cbLoss_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbLoss.SelectedIndex >= 0)
            {
                lossID = Convert.ToInt32(cbLoss.SelectedValue);
            }
            else
                lossID = 0;
        }

        private void chbPFSH_CheckedChanged(object sender, EventArgs e)
        {
            groupBoxPFSH.Enabled = chbPFSH.Checked;
        }

        private void chbYear_CheckedChanged(object sender, EventArgs e)
        {
            cbYear.Enabled = chbYear.Checked;
        }

        private void chbLoss_CheckedChanged(object sender, EventArgs e)
        {
            cbLoss.Enabled = chbLoss.Checked;
        }

        private void buttonShow_Click(object sender, EventArgs e)
        {
            int? schID, lID, yr;

            if (chbPFSH.Checked && pfshID > 0)
                schID = pfshID;
            else
                schID = null;

            if (chbLoss.Checked && this.lossID > 0)
                lID = this.lossID;
            else
                lID = null;

            if (chbYear.Checked && year > 1991)
                yr = year;
            else
                yr = null;

            dgvSchoolLosses.DataSource = DBClass.RESPContext.SchoolLossReport(InformationClass.Lang, schID, lID, yr);

            if (InformationClass.Lang)
            {
                dgvSchoolLosses.Columns["Name"].HeaderText = "ПФШ";
                dgvSchoolLosses.Columns["LossName"].HeaderText = "Наименование затраты";
                dgvSchoolLosses.Columns["Measure"].HeaderText = "Ед. измерения";
                dgvSchoolLosses.Columns["Amount"].HeaderText = "Величина затрат, сум/га";
            }
            else
            {
                dgvSchoolLosses.Columns["Name"].HeaderText = "ДФМ";
                dgvSchoolLosses.Columns["LossName"].HeaderText = "Ҳаражатслар номи";
                dgvSchoolLosses.Columns["Measure"].HeaderText = "Ўлчов бирлиги";
                dgvSchoolLosses.Columns["Amount"].HeaderText = "Ҳаражатлар миқдори, сўм/га";
            }


            dgvSchoolLosses.AutoResizeColumns();
        }

        private void buttonExcel_Click(object sender, EventArgs e)
        {
            if (dgvSchoolLosses.RowCount > 0)
            {
                MessageBox.Show(msgClass.msgWaiting);
                GetReport();
                excelapp.Visible = true;
            }
        }

        Sheets excelsheets;
        Worksheet excelworksheet;
        Microsoft.Office.Interop.Excel.Application excelapp;
        Workbook excelappworkbook;

        private void GetReport()
        {
            excelapp = new Microsoft.Office.Interop.Excel.Application();
            excelapp.SheetsInNewWorkbook = 1;

            if (InformationClass.Lang)
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\i19.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            else
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\i19uz.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            excelappworkbook = excelapp.Workbooks[1];
            excelsheets = excelappworkbook.Worksheets;// .Worksheets[0]; //Sheets 

            int numPage = 1, left = 2, top = 11;

            excelworksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelsheets.get_Item(numPage);

            excelworksheet.Cells.NumberFormat = "@";

            if (chbPFSH.Checked)
            {
                excelworksheet.Cells[4, 3] = cbRegion.Text;
                excelworksheet.Cells[5, 3] = cbAVP.Text;
                excelworksheet.Cells[6, 3] = cbFH.Text;
                excelworksheet.Cells[7, 3] = cbPFSH.Text;
            }
            if (chbYear.Checked)
                excelworksheet.Cells[9, 2] = InformationClass.Lang ? "Год: " + cbYear.Text : "Йил: " + cbYear.Text;


            for (int i = 0; i < dgvSchoolLosses.Rows.Count; i++)
            {
                for (int j = 1; j < dgvSchoolLosses.Columns.Count; j++)
                {
                    excelworksheet.Cells[i + top, dgvSchoolLosses.Columns[j].DisplayIndex + left] = dgvSchoolLosses[j, i].FormattedValue;
                    addBorder(excelworksheet.Cells[i + top, dgvSchoolLosses.Columns[j].DisplayIndex + left]);
                }
                excelworksheet.Cells[i + top, 2] = i + 1;
                addBorder(excelworksheet.Cells[i + top, 2]);
            }
            excelworksheet.Columns.AutoFit();
            excelworksheet.Select(numPage);
        }

        private void addBorder(object p)
        {
            Range tmpRange = excelworksheet.get_Range(p, p);
            tmpRange.Borders[XlBordersIndex.xlEdgeLeft].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeRight].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeTop].LineStyle = XlLineStyle.xlContinuous;
        }

        private void dgvSchoolLosses_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dgvSchoolLosses.Columns.Contains("Measure"))
            {
                if (e.ColumnIndex.Equals(dgvSchoolLosses.Columns["Measure"].Index) && e.Value != null)
                {
                    e.Value = UtilClass.GetCategoryDisplayName((int)e.Value, "Dimension");
                }
            }
            if (dgvSchoolLosses.Columns.Contains("Amount"))
            {
                if (e.ColumnIndex.Equals(dgvSchoolLosses.Columns["Amount"].Index) && e.Value != null)
                {
                    e.Value = ((decimal)e.Value).ToString("N2");
                }
            }
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            if (dgvSchoolLosses.RowCount > 0)
                PrintDGV.Print_DataGridView(dgvSchoolLosses);
        }
    }
}
